package com.dikeleakagedetection.myapplication.ui.database

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.dikeleakagedetection.myapplication.DikeLeakageDetectionApp
import com.dikeleakagedetection.myapplication.databinding.FragDatabaseBinding
import com.dikeleakagedetection.myapplication.logic.dao.Tablet
import com.dikeleakagedetection.myapplication.logic.dao.AppDatabase

import kotlin.collections.ArrayList
import kotlin.concurrent.thread


class DatabaseFragment : Fragment() {

    private lateinit var databaseViewModel: DatabaseViewModel

    private lateinit var binding: FragDatabaseBinding

    private val tabletList = ArrayList<Tablet>()
    private val tabletDao = AppDatabase.getDatabase(DikeLeakageDetectionApp.context).tabletDao()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        databaseViewModel = ViewModelProvider(this).get(DatabaseViewModel::class.java)
        binding = FragDatabaseBinding.inflate(inflater, container, false)

        val layoutManager = GridLayoutManager(activity, 3)
        val tabletAdapter = TabletAdapter(this, tabletList)
        binding.rvTabletsFragDatabase.adapter = tabletAdapter
        binding.rvTabletsFragDatabase.layoutManager = layoutManager
        initTablets()
        return binding.root
    }

    private fun initTablets() {
        thread {
            for(tablet in tabletDao.loadTabletByUserId(DikeLeakageDetectionApp.user.id)){
                tabletList.add(tablet)
            }

            Log.e("数据库",tabletList.size.toString())

            activity?.runOnUiThread {
                binding.rvTabletsFragDatabase.adapter!!.notifyDataSetChanged()
            }

        }
    }
}